package cn.tedu.person.security;

import cn.tedu.person.mapper.AdminMapper;
import cn.tedu.person.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security自动调用了loadUseByUsername()" +
                "的方法，参数{}",s);

        AdminLoginInfoVO loginInfoVO=adminMapper.getLoginInfoByUsername(s);
        log.debug("根据用户名【{}】查询登录信息,结果：{}",s,loginInfoVO);
        if(loginInfoVO == null){
            String message="用户名【{}】不存在，将不会返回有效的userDetails,则返回null";
            log.warn(message);
            return null;
        }

        Collection<GrantedAuthority> authorities=new ArrayList<>();
        for (String permission : loginInfoVO.getPermissions()) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }

        AdminDetails adminDetails=new AdminDetails(
                loginInfoVO.getId(),
                loginInfoVO.getName(),
                loginInfoVO.getPassword(),
                loginInfoVO.getEnable()==1,
                authorities);

        return adminDetails;
    }
}
